from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.db.models import Q, Count, Min, Max, Avg
from django.core.paginator import Paginator
from django.db import models
import json
import threading
from .models import Category, Product, ApiLog, SyncTask
from .services import EbayApiService


class CategoryListView(View):
    """类目列表API"""
    
    def get(self, request):
        try:
            # 获取查询参数
            level = request.GET.get('level')
            parent_id = request.GET.get('parent_id')
            search = request.GET.get('search')
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 20))
            
            # 构建查询
            queryset = Category.objects.all()
            
            if level:
                queryset = queryset.filter(level=level)
            
            if parent_id:
                queryset = queryset.filter(parent_id=parent_id)
            
            if search:
                queryset = queryset.filter(
                    Q(category_name__icontains=search) |
                    Q(category_id__icontains=search)
                )
            
            # 按层级和ID排序
            queryset = queryset.order_by('level', 'category_id')
            
            # 分页
            paginator = Paginator(queryset, page_size)
            categories = paginator.get_page(page)
            
            # 构建响应数据
            data = []
            for category in categories:
                item = {
                    'category_id': category.category_id,
                    'category_name': category.category_name,
                    'parent_id': category.parent_id,
                    'level': category.level,
                    'leaf_category': category.leaf_category,
                    'category_path': category.category_path,
                    'children_count': category.children.count(),
                    'product_count': Product.objects.filter(ebay_category_id=category.category_id).count(),
                    'created_at': category.created_at.isoformat(),
                }
                data.append(item)
            
            return JsonResponse({
                'success': True,
                'data': data,
                'pagination': {
                    'page': page,
                    'page_size': page_size,
                    'total_pages': paginator.num_pages,
                    'total_count': paginator.count,
                    'has_next': categories.has_next(),
                    'has_previous': categories.has_previous(),
                }
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)


class CategoryDetailView(View):
    """类目详情API"""
    
    def get(self, request, category_id):
        try:
            category = get_object_or_404(Category, category_id=category_id)
            
            # 获取父类目
            parent = None
            if category.parent_id:
                parent_obj = Category.objects.filter(category_id=category.parent_id).first()
                if parent_obj:
                    parent = {
                        'category_id': parent_obj.category_id,
                        'category_name': parent_obj.category_name,
                        'level': parent_obj.level,
                    }
            
            # 获取子类目
            children = []
            for child in category.children:
                children.append({
                    'category_id': child.category_id,
                    'category_name': child.category_name,
                    'level': child.level,
                    'leaf_category': child.leaf_category,
                    'product_count': Product.objects.filter(ebay_category_id=child.category_id).count(),
                })
            
            data = {
                'category_id': category.category_id,
                'category_name': category.category_name,
                'parent_id': category.parent_id,
                'level': category.level,
                'leaf_category': category.leaf_category,
                'category_path': category.category_path,
                'parent': parent,
                'children': children,
                'product_count': Product.objects.filter(ebay_category_id=category.category_id).count(),
                'created_at': category.created_at.isoformat(),
                'updated_at': category.updated_at.isoformat(),
            }
            
            return JsonResponse({
                'success': True,
                'data': data
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)


class ProductListView(View):
    """商品列表API"""
    
    def get(self, request):
        try:
            # 获取查询参数
            category_id = request.GET.get('category_id')
            search = request.GET.get('search')
            min_price = request.GET.get('min_price')
            max_price = request.GET.get('max_price')
            condition = request.GET.get('condition')
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 20))
            
            # 构建查询
            queryset = Product.objects.select_related('category')
            
            if category_id:
                queryset = queryset.filter(ebay_category_id=category_id)
            
            if search:
                queryset = queryset.filter(
                    Q(title__icontains=search) |
                    Q(item_id__icontains=search) |
                    Q(seller_username__icontains=search)
                )
            
            if min_price:
                queryset = queryset.filter(current_price__gte=float(min_price))
            
            if max_price:
                queryset = queryset.filter(current_price__lte=float(max_price))
            
            if condition:
                queryset = queryset.filter(condition__icontains=condition)
            
            # 按创建时间倒序
            queryset = queryset.order_by('-created_at')
            
            # 分页
            paginator = Paginator(queryset, page_size)
            products = paginator.get_page(page)
            
            # 构建响应数据
            data = []
            for product in products:
                item = {
                    'item_id': product.item_id,
                    'title': product.title,
                    'category': {
                        'category_id': product.category.category_id,
                        'category_name': product.category.category_name,
                        'level': product.category.level,
                    } if product.category else None,
                    'current_price': float(product.current_price) if product.current_price else None,
                    'currency': product.currency,
                    'condition': product.condition,
                    'listing_type': product.listing_type,
                    'seller_username': product.seller_username,
                    'seller_feedback_score': product.seller_feedback_score,
                    'gallery_url': product.gallery_url,
                    'view_item_url': product.view_item_url,
                    'location': product.location,
                    'created_at': product.created_at.isoformat(),
                }
                data.append(item)
            
            return JsonResponse({
                'success': True,
                'data': data,
                'pagination': {
                    'page': page,
                    'page_size': page_size,
                    'total_pages': paginator.num_pages,
                    'total_count': paginator.count,
                    'has_next': products.has_next(),
                    'has_previous': products.has_previous(),
                }
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)


class ProductDetailView(View):
    """商品详情API"""
    
    def get(self, request, item_id):
        try:
            product = get_object_or_404(Product, item_id=item_id)
            
            data = {
                'item_id': product.item_id,
                'title': product.title,
                'category': {
                    'category_id': product.category.category_id,
                    'category_name': product.category.category_name,
                    'level': product.category.level,
                    'category_path': product.category.category_path,
                } if product.category else None,
                'current_price': float(product.current_price) if product.current_price else None,
                'currency': product.currency,
                'condition': product.condition,
                'listing_type': product.listing_type,
                'buy_it_now_price': float(product.buy_it_now_price) if product.buy_it_now_price else None,
                'seller_username': product.seller_username,
                'seller_feedback_score': product.seller_feedback_score,
                'gallery_url': product.gallery_url,
                'view_item_url': product.view_item_url,
                'shipping_cost': float(product.shipping_cost) if product.shipping_cost else None,
                'location': product.location,
                'start_time': product.start_time.isoformat() if product.start_time else None,
                'end_time': product.end_time.isoformat() if product.end_time else None,
                'watch_count': product.watch_count,
                'bid_count': product.bid_count,
                'raw_data': product.raw_data,
                'created_at': product.created_at.isoformat(),
                'updated_at': product.updated_at.isoformat(),
            }
            
            return JsonResponse({
                'success': True,
                'data': data
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)


@method_decorator(csrf_exempt, name='dispatch')
class SyncCategoriesView(View):
    """同步类目API"""
    
    def post(self, request):
        try:
            def run_sync():
                try:
                    service = EbayApiService()
                    saved_count = service.sync_all_categories()
                    print(f"类目同步完成，共保存 {saved_count} 个类目")
                except Exception as e:
                    print(f"类目同步失败: {e}")
            
            # 在后台线程中运行同步
            thread = threading.Thread(target=run_sync)
            thread.daemon = True
            thread.start()
            
            return JsonResponse({
                'success': True,
                'message': '类目同步任务已启动，请稍后查看结果'
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)


@method_decorator(csrf_exempt, name='dispatch')
class SyncProductsView(View):
    """同步商品API"""
    
    def post(self, request, category_id):
        try:
            # 检查类目是否存在
            category = get_object_or_404(Category, category_id=category_id)
            
            # 获取参数
            data = json.loads(request.body) if request.body else {}
            max_items = data.get('max_items', 10000)
            
            def run_sync():
                try:
                    service = EbayApiService()
                    saved_count = service.sync_products_by_category(category_id, max_items)
                    print(f"类目 {category_id} 商品同步完成，共保存 {saved_count} 个商品")
                except Exception as e:
                    print(f"商品同步失败: {e}")
            
            # 在后台线程中运行同步
            thread = threading.Thread(target=run_sync)
            thread.daemon = True
            thread.start()
            
            return JsonResponse({
                'success': True,
                'message': f'类目 {category.category_name} 的商品同步任务已启动'
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)


def category_tree_view(request):
    """类目树状结构视图（可选）"""
    try:
        # 获取一级类目
        level1_categories = Category.objects.filter(level=1).order_by('category_id')
        
        tree_data = []
        for cat1 in level1_categories:
            # 获取二级类目
            level2_categories = Category.objects.filter(parent_id=cat1.category_id).order_by('category_id')
            
            cat1_data = {
                'category_id': cat1.category_id,
                'category_name': cat1.category_name,
                'level': cat1.level,
                'product_count': Product.objects.filter(ebay_category_id=cat1.category_id).count(),
                'children': []
            }
            
            for cat2 in level2_categories:
                # 获取三级类目
                level3_categories = Category.objects.filter(parent_id=cat2.category_id).order_by('category_id')
                
                cat2_data = {
                    'category_id': cat2.category_id,
                    'category_name': cat2.category_name,
                    'level': cat2.level,
                    'product_count': Product.objects.filter(ebay_category_id=cat2.category_id).count(),
                    'children': []
                }
                
                for cat3 in level3_categories:
                    cat3_data = {
                        'category_id': cat3.category_id,
                        'category_name': cat3.category_name,
                        'level': cat3.level,
                        'product_count': Product.objects.filter(ebay_category_id=cat3.category_id).count(),
                        'children': []
                    }
                    cat2_data['children'].append(cat3_data)
                
                cat1_data['children'].append(cat2_data)
            
            tree_data.append(cat1_data)
        
        if request.content_type == 'application/json':
            return JsonResponse({
                'success': True,
                'data': tree_data
            })
        else:
            return render(request, 'ebay/category_tree.html', {'tree_data': tree_data})
            
    except Exception as e:
        if request.content_type == 'application/json':
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)
        else:
            return render(request, 'ebay/error.html', {'error': str(e)})


def product_list(request):
    """产品列表页面"""
    # 获取筛选参数
    level1_id = request.GET.get('level1')
    level2_id = request.GET.get('level2')
    level3_id = request.GET.get('level3')
    date_range = request.GET.get('date_range')
    category_type = request.GET.get('category_type')
    search = request.GET.get('search', '')
    
    # 新增筛选参数
    min_price = request.GET.get('min_price')
    max_price = request.GET.get('max_price')
    condition = request.GET.get('condition')
    listing_type = request.GET.get('listing_type')
    location = request.GET.get('location')
    currency = request.GET.get('currency')
    
    # 基础查询
    products = Product.objects.select_related('category').all()
    
    # 类目筛选
    if level3_id:
        products = products.filter(ebay_category_id=level3_id)
    elif level2_id:
        products = products.filter(ebay_category_id=level2_id)
    elif level1_id:
        products = products.filter(ebay_category_id=level1_id)
    
    # 日期筛选
    if date_range:
        from datetime import datetime, timedelta
        now = datetime.now()
        
        if date_range == 'today':
            products = products.filter(created_at__date=now.date())
        elif date_range == 'yesterday':
            yesterday = now - timedelta(days=1)
            products = products.filter(created_at__date=yesterday.date())
        elif date_range == 'this_week':
            start = now - timedelta(days=now.weekday())
            products = products.filter(created_at__date__gte=start.date())
        elif date_range == 'last_week':
            start = now - timedelta(days=now.weekday() + 7)
            end = now - timedelta(days=now.weekday() + 1)
            products = products.filter(created_at__date__range=[start.date(), end.date()])
        elif date_range == 'this_month':
            products = products.filter(created_at__year=now.year, created_at__month=now.month)
        elif date_range == 'last_month':
            last_month = now.replace(day=1) - timedelta(days=1)
            products = products.filter(created_at__year=last_month.year, created_at__month=last_month.month)
    
    # 蓝海/红海筛选
    if category_type:
        if category_type == 'blue':
            blue_categories = Category.objects.annotate(
                product_count=Count('product')
            ).filter(product_count__lt=100).values_list('category_id', flat=True)
            products = products.filter(ebay_category_id__in=blue_categories)
        elif category_type == 'red':
            red_categories = Category.objects.annotate(
                product_count=Count('product')
            ).filter(product_count__gte=100).values_list('category_id', flat=True)
            products = products.filter(ebay_category_id__in=red_categories)
    
    # 关键词搜索（扩展到包含描述和更多字段）
    if search:
        products = products.filter(
            Q(title__icontains=search) |
            Q(item_id__icontains=search) |
            Q(category__category_name__icontains=search) |
            Q(seller_username__icontains=search) |
            Q(location__icontains=search) |
            Q(condition__icontains=search)
        )
    
    # 价格范围筛选
    if min_price:
        try:
            min_price_value = float(min_price)
            products = products.filter(current_price__gte=min_price_value)
        except (ValueError, TypeError):
            pass
    
    if max_price:
        try:
            max_price_value = float(max_price)
            products = products.filter(current_price__lte=max_price_value)
        except (ValueError, TypeError):
            pass
    
    # 商品状态筛选
    if condition:
        products = products.filter(condition__icontains=condition)
    
    # 销售类型筛选
    if listing_type:
        products = products.filter(listing_type__icontains=listing_type)
    
    # 位置筛选
    if location:
        products = products.filter(location__icontains=location)
    
    # 货币筛选
    if currency:
        products = products.filter(currency=currency)
    
    # 排序（扩展更多选项）
    sort_by = request.GET.get('sort', '-created_at')
    valid_sort_options = [
        '-created_at', 'created_at',           # 时间排序
        'current_price', '-current_price',     # 价格排序
        'title', '-title',                     # 标题排序
        '-watch_count', 'watch_count',         # 人气排序（关注数）
        '-bid_count', 'bid_count',             # 出价次数排序
        '-seller_feedback_score', 'seller_feedback_score',  # 卖家评分排序
        '-end_time', 'end_time',               # 结束时间排序
    ]
    
    if sort_by in valid_sort_options:
        # 处理空值排序问题
        if sort_by in ['-watch_count', 'watch_count']:
            products = products.extra(select={'watch_count_null': 'watch_count IS NULL'}).order_by('watch_count_null', sort_by)
        elif sort_by in ['-bid_count', 'bid_count']:
            products = products.extra(select={'bid_count_null': 'bid_count IS NULL'}).order_by('bid_count_null', sort_by)
        elif sort_by in ['current_price', '-current_price']:
            products = products.extra(select={'price_null': 'current_price IS NULL'}).order_by('price_null', sort_by)
        else:
            products = products.order_by(sort_by)
    else:
        products = products.order_by('-created_at')
    
    # 分页
    paginator = Paginator(products, 20)  # 每页20个产品
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取类目数据
    level1_categories = Category.objects.filter(level=1).annotate(
        product_count=Count('product')
    ).order_by('category_name')
    
    level2_categories = []
    level3_categories = []
    
    if level1_id:
        level2_categories = Category.objects.filter(
            parent_id=level1_id,
            level=2
        ).annotate(
            product_count=Count('product')
        ).order_by('category_name')
        
        if level2_id:
            level3_categories = Category.objects.filter(
                parent_id=level2_id,
                level=3
            ).annotate(
                product_count=Count('product')
            ).order_by('category_name')
    
    # 获取选中的类目信息
    selected_categories = {}
    if level1_id:
        try:
            selected_categories['level1'] = Category.objects.get(category_id=level1_id)
        except Category.DoesNotExist:
            pass
    
    if level2_id:
        try:
            selected_categories['level2'] = Category.objects.get(category_id=level2_id)
        except Category.DoesNotExist:
            pass
    
    if level3_id:
        try:
            selected_categories['level3'] = Category.objects.get(category_id=level3_id)
        except Category.DoesNotExist:
            pass
    
    # 获取筛选选项数据
    conditions = Product.objects.values_list('condition', flat=True).distinct().exclude(condition__isnull=True).exclude(condition='')
    listing_types = Product.objects.values_list('listing_type', flat=True).distinct().exclude(listing_type__isnull=True).exclude(listing_type='')
    locations = Product.objects.values_list('location', flat=True).distinct().exclude(location__isnull=True).exclude(location='')[:50]  # 限制50个位置
    currencies = Product.objects.values_list('currency', flat=True).distinct().exclude(currency__isnull=True).exclude(currency='')
    
    # 价格范围统计
    price_stats = products.aggregate(
        min_price=Min('current_price'),
        max_price=Max('current_price'),
        avg_price=Avg('current_price')
    )
    
    context = {
        'products': page_obj,
        'level1_categories': level1_categories,
        'level2_categories': level2_categories,
        'level3_categories': level3_categories,
        'selected_categories': selected_categories,
        'selected_level1': level1_id,
        'selected_level2': level2_id,
        'selected_level3': level3_id,
        'selected_date_range': date_range,
        'selected_category_type': category_type,
        'search_query': search,
        'sort_by': sort_by,
        'total_count': paginator.count,
        
        # 新增筛选参数
        'min_price': min_price,
        'max_price': max_price,
        'selected_condition': condition,
        'selected_listing_type': listing_type,
        'selected_location': location,
        'selected_currency': currency,
        
        # 筛选选项数据
        'conditions': list(conditions),
        'listing_types': list(listing_types),
        'locations': list(locations),
        'currencies': list(currencies),
        'price_stats': price_stats,
    }
    
    return render(request, 'ebay/product_list.html', context)


def get_subcategories(request):
    """AJAX接口：获取子类目"""
    parent_id = request.GET.get('parent_id')
    level = int(request.GET.get('level', 2))
    
    if not parent_id:
        return JsonResponse({'categories': []})
    
    categories = Category.objects.filter(
        parent_id=parent_id,
        level=level
    ).annotate(
        product_count=Count('product')
    ).order_by('category_name')
    
    category_list = [
        {
            'category_id': cat.category_id,
            'category_name': cat.category_name,
            'product_count': cat.product_count
        }
        for cat in categories
    ]
    
    return JsonResponse({'categories': category_list})
